<template>
  <div>
    <el-dialog
      width="700px"
      :visible="sourceTableQueryConditionsVisible"
      title="源表查询条件"
      @close="handleSourceClose"
    >
      <!-- 💭循环层 -->
      <div style="margin-bottom: 8px" v-for="item in sourceColumns" :key="item.id">
        <!-- 0. 删除 -->
        <i class="el-icon-delete" style="margin-right: 4px" @click="handleDelete(item)"></i>
        <!-- 1. 并且或者 -->
        <el-select v-if="item.conjunction" v-model="item.conjunction" size="mini" style="width: 15%; margin-right: 4px" filterable clearable>
          <el-option label="并且" value="&&"></el-option>
          <el-option label="或者" value="||"></el-option>
        </el-select>
        <!-- 2. 固定值不可选 -->
        <el-select v-model="item.fixed" size="mini" style="width: 20%; margin-right: 4px" disabled>
          <el-option
            v-for="item in sourceTableQueryConditionsOptions"
            :key="item.variable"
            :value="item.variable"
            :label="item.variableName"
          ></el-option>
        </el-select>
        <!-- 3. 等于 -->
        <el-select v-model="item.comparator" size="mini" style="width: 15%; margin-right: 4px">
          <el-option
            v-for="item in comparatorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- 4. 输入值 -->
        <span v-if="item.comparator !== '不为空' && item.comparator !== '为空'">
          <el-input-number
            v-if="item.numberOrSelect === 'number'"
            v-model="item.number"
            size="mini"
            style="width: 20%; margin-right: 4px"
          ></el-input-number>
          <!-- 选择值 -->
          <el-select
            v-if="item.numberOrSelect === 'select'"
            v-model="item.selectVal"
            size="mini"
            style="width: 20%; margin-right: 4px"
          >
            <el-option
              v-for="item in item.selectValOptions"
              :key="item.codeValue"
              :label="item.codeDescribe"
              :value="item.codeValue"
            ></el-option>
          </el-select>
        </span>
      </div>
      <!-- 💭固定层 -->
      <div>
        <el-select
          size="mini"
          placeholder="选择本表字段"
          v-model="sourceTableQueryConditionsValue"
          style="margin-right: 4px; width: 20%"
        >
          <el-option
            v-for="item in sourceTableQueryConditionsOptions"
            :key="item.variable"
            :value="item.variable"
            :label="item.variableName"
          ></el-option>
        </el-select>
        <el-button type="primary" size="mini" @click="handleSourceAdd()">增加条件</el-button>
      </div>
      <!-- 💭底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleSourceClose">取 消</el-button>
        <el-button size="small" type="primary" @click="handleSourceSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash-es'
import { generateRandomId } from '@/utils/modules/crossConLogic.js'
import { comparatorOptions, comparatorOptionsEnums } from '../data'
import { mapActions } from 'vuex'
import { checkPropertiesNotEmpty } from '@/utils/modules/tableConLogic.js'
export default {
  props: {
    sourceTableQueryConditionsVisible: {
      type: Boolean,
    },
    sourceTableQueryConditionsOptions: {
      type: Array,
    },
    sourceTableQueryConditionsOptionsEnums: {
      type: Object,
    },
    sourceTableList: {
      type: Array,
    },
    formData: {
      type: Object,
    },
    surface: {
      type: String,
    },
    sourceConditionRemark: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      sourceTableQueryConditionsValue: '',
      sourceColumns: [],
      comparatorOptions,
      comparatorOptionsEnums,
      conjunctionOpitonsEnums: {
        '&&': '并且',
        '||': '或者',
      },
      projectId: '',
      databaseId: '',
      databaseVersion: '',
      code_name: '',
      databaseInfo: '',
      selectValOptions: [],
      selectValOptionsEnums: {},
    }
  },

  watch: {
    sourceTableQueryConditionsVisible(newV, oldV) {
      if (newV) {
        if (Array.isArray(this.sourceConditionRemark)) {
          this.sourceColumns = this.sourceConditionRemark
        }
      }
    },
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.databaseId = this.databaseInfo.databaseId || ''
    this.databaseVersion = this.databaseInfo.databaseVersion || ''
  },
  methods: {
    ...mapActions('eCRFDesign', ['qryCodeValueByCodeNameNoLoading']),
    // 获取特殊下拉项
    async getSelectValOptions(codeName) {
      const params = {
        projectId: this.projectId,
        databaseId: this.databaseId,
        databaseVersion: this.databaseVersion,
        code_name: codeName,
        surface: this.surface,
      }
      const res = await this.qryCodeValueByCodeNameNoLoading({ params })
      this.selectValOptions = res.data
      res.data.forEach(item => {
        this.selectValOptionsEnums[item.codeValue] = item.codeDescribe
      })
    },
    // 1. 点击增加
    async handleSourceAdd() {
      if (!this.sourceTableQueryConditionsValue) return this.$message.warning('请选择本表字段!')
      const typeObj = this.sourceTableQueryConditionsOptions.find(
        item => item.variable === this.sourceTableQueryConditionsValue
      )
      const variableType = typeObj.variableType
      const arr = ['10', '20']
      const flag = arr.includes(variableType)
      // 区分不同字段类型
      // select
      if (flag) {
        const codeName = typeObj.variableTypeValue.codeName.split('|')[0].trim()
        await this.getSelectValOptions(codeName)
        if (this.sourceTableQueryConditionsValue) {
          if (this.sourceColumns.length === 0) {
            this.sourceColumns.push({
              numberOrSelect: 'select',
              fixed: this.sourceTableQueryConditionsValue,
              comparator: '==',
              selectVal: '',
              selectValOptions: this.selectValOptions,
              id: generateRandomId(),
            })
          } else {
            this.sourceColumns.push({
              numberOrSelect: 'select',
              conjunction: '&&',
              fixed: this.sourceTableQueryConditionsValue,
              comparator: '==',
              selectVal: '',
              selectValOptions: this.selectValOptions,
              id: generateRandomId(),
            })
          }
        }
        // number
      } else {
        if (this.sourceTableQueryConditionsValue) {
          if (this.sourceColumns.length === 0) {
            this.sourceColumns.push({
              numberOrSelect: 'number',
              fixed: this.sourceTableQueryConditionsValue,
              comparator: '==',
              number: 0,
              id: generateRandomId(),
            })
          } else {
            this.sourceColumns.push({
              numberOrSelect: 'number',
              conjunction: '&&',
              fixed: this.sourceTableQueryConditionsValue,
              comparator: '==',
              number: 0,
              id: generateRandomId(),
            })
          }
        }
      }
    },
    // 2. 删除
    handleDelete(ite) {
      this.sourceColumns = this.sourceColumns.filter(item => {
        return item.id !== ite.id
      })
    },
    // 4. 确认
    handleSourceSave() {
      // 进行非空校验
      const arr = cloneDeep(this.sourceColumns)
      arr.forEach(item => {
        if (item.comparator === '为空' || item.comparator === '不为空') {
          delete item.selectVal
          delete item.selectValOptions
          delete item.number
        }
      })
      const isNotEmpty = checkPropertiesNotEmpty(arr)
      if (isNotEmpty) {
        let paramString = ''
        let paramStringTwo = ''
        // 获取表名
        const tableCode = this.formData.sourceTableCrf
        // 字段拼接
        this.sourceColumns.forEach(item => {
          // 🏀非第一个
          if (item.conjunction) {
            if (item.comparator === '为空') {
              paramString =
                paramString +
                ' ' +
                this.conjunctionOpitonsEnums[item.conjunction] +
                ' ' +
                this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                ' ' +
                '为空'
              paramStringTwo =
                paramStringTwo +
                ' ' +
                item.conjunction +
                ' ' +
                '(' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '==' +
                ' ' +
                "'null'" +
                ' ' +
                '||' +
                ' ' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '==' +
                ' ' +
                "''" +
                ')'
            } else if (item.comparator === '不为空') {
              paramString =
                paramString +
                ' ' +
                this.conjunctionOpitonsEnums[item.conjunction] +
                ' ' +
                this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                ' ' +
                '不为空'
              paramStringTwo =
                paramStringTwo +
                ' ' +
                item.conjunction +
                ' ' +
                '(' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '!=' +
                ' ' +
                "'null'" +
                ' ' +
                '||' +
                ' ' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '!=' +
                ' ' +
                "''" +
                ')'
            } else {
              // 数值
              if (item.numberOrSelect === 'number') {
                // 中文
                paramString =
                  paramString +
                  ' ' +
                  this.conjunctionOpitonsEnums[item.conjunction] +
                  ' ' +
                  this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                  ' ' +
                  this.comparatorOptionsEnums[item.comparator] +
                  ' ' +
                  item.number
                // 非中文
                paramStringTwo =
                  paramStringTwo +
                  ' ' +
                  item.conjunction +
                  ' ' +
                  tableCode +
                  '.' +
                  item.fixed +
                  ' ' +
                  item.comparator +
                  ' ' +
                  item.number
                // 选择
              } else {
                // 中文
                paramString =
                  paramString +
                  ' ' +
                  this.conjunctionOpitonsEnums[item.conjunction] +
                  ' ' +
                  this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                  ' ' +
                  this.comparatorOptionsEnums[item.comparator] +
                  ' ' +
                  this.selectValOptionsEnums[item.selectVal]
                // 非中文
                paramStringTwo =
                  paramStringTwo +
                  ' ' +
                  item.conjunction +
                  ' ' +
                  tableCode +
                  '.' +
                  item.fixed +
                  ' ' +
                  item.comparator +
                  ' ' +
                  item.selectVal
              }
            }
            // 🏀第一个
          } else {
            if (item.comparator === '为空') {
              paramString = paramString + this.sourceTableQueryConditionsOptionsEnums[item.fixed] + ' ' + '为空'
              paramStringTwo =
                paramStringTwo +
                '(' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '==' +
                ' ' +
                "'null'" +
                ' ' +
                '||' +
                ' ' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '==' +
                ' ' +
                "''" +
                ')'
            } else if (item.comparator === '不为空') {
              paramString = paramString + this.sourceTableQueryConditionsOptionsEnums[item.fixed] + ' ' + '不为空'
              paramStringTwo =
                paramStringTwo +
                '(' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '!=' +
                ' ' +
                "'null'" +
                ' ' +
                '||' +
                ' ' +
                tableCode +
                '.' +
                item.fixed +
                ' ' +
                '!=' +
                ' ' +
                "''" +
                ')'
            } else {
              // 数值
              if (item.numberOrSelect === 'number') {
                // 中文
                paramString =
                  paramString +
                  this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                  ' ' +
                  this.comparatorOptionsEnums[item.comparator] +
                  ' ' +
                  item.number
                // 非中文
                paramStringTwo =
                  paramStringTwo + tableCode + '.' + item.fixed + ' ' + item.comparator + ' ' + item.number
                // 选择
              } else {
                // 中文
                paramString =
                  paramString +
                  this.sourceTableQueryConditionsOptionsEnums[item.fixed] +
                  ' ' +
                  this.comparatorOptionsEnums[item.comparator] +
                  ' ' +
                  this.selectValOptionsEnums[item.selectVal]
                // 非中文
                paramStringTwo =
                  paramStringTwo + tableCode + '.' + item.fixed + ' ' + item.comparator + ' ' + item.selectVal
              }
            }
          }
        })
        // 字符串传递给父组件
        this.$emit('transmitString', {
          paramString,
          paramStringTwo,
          sourceColumns: this.sourceColumns,
        })
        this.handleSourceClose()
      } else {
        this.$message.warning('请填写完整！')
      }
    },
    // 3. 取消
    handleSourceClose() {
      this.sourceTableQueryConditionsValue = ''
      this.$emit('update:sourceTableQueryConditionsVisible', false)
    },
  },
}
</script>

<style lang="scss" scoped></style>
